package com.banciyuan.bcywebview.biz.ask;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.activity.BasePullLoadActivity;
import com.banciyuan.bcywebview.base.factory.AskFactory;
import com.banciyuan.bcywebview.base.helper.FlagUtils;
import com.banciyuan.bcywebview.base.helper.LoadingHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.util.BaseWatcher;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase.OnLastItemVisibleListener;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.ask.ask.WriteAskActivity;
import com.banciyuan.bcywebview.biz.ask.question.QuestionActivity;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.daoexample.model.Ask;
import de.greenrobot.daoexample.model.AskHeaderInfo;

/**
 * @author hfxt2008
 *         <p/>
 *         首页个人页面/个人空间页面/ASK卡片->ASK页面
 */
public class AskActivity extends BasePullLoadActivity implements OnClickListener, BaseWatcher {

    private static final int FROM_ASK = 554;

    private PullToRefreshListView mRefreshLv;
    private ListView mContentLv;
    private TextView mOthersAskTv;
    private TextView mQuestionTv;
    private TextView mAnswerNum;
    private AskListviewAdapter mAdapter;
    private LoadingHelper mProgressbarHelper;
    private AskHelper mHelper;
    private String ouid;
    private String mName;
    private TextView mAskTvTop;

    private List<Ask> alist = new ArrayList<>();
    private AskHeaderInfo askHeaderInfo;

    private int page = 1;
    private boolean is_load;
    private boolean is_end;

    private View parent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        parent = View.inflate(this, R.layout.ask_newlayout, null);
        setContentView(parent);
        initArgs();
        initProgressbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        BaseObserver.getInstance().addWatcher(AskActivity.class, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        BaseObserver.getInstance().removeWatcher(AskActivity.class);
    }

    @Override
    public void selfUpdateData() {
        mRefreshLv.setRefreshing();
    }

    @Override
    protected void initArgs() {
        mHelper = new AskHelper(this);
        ouid = StringUtil.getString(getIntent(), gotoUtil.INTENT_VALUE_ONE);
        mName = StringUtil.getString(getIntent(), gotoUtil.INTENT_VALUE_TWO);
    }

    @Override
    protected void initProgressbar() {
        mProgressbarHelper = new LoadingHelper(parent);
        mProgressbarHelper.setActionCallbacks(new LoadingHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                if (!is_load) {
                    resetData();
                    mProgressbarHelper.onLoading();
                    initData();
                }
            }
        });
        mProgressbarHelper.onLoading();
    }

    private void resetData() {
        is_load = true;
        is_end = false;
        page = 1;
    }

    @Override
    protected void initUi() {

        mOthersAskTv = (TextView) findViewById(R.id.ask_othersask_tv);
        mQuestionTv = (TextView) findViewById(R.id.ask_question_tv);
        findViewById(R.id.iv_back).setOnClickListener(this);
        mRefreshLv = (PullToRefreshListView) findViewById(R.id.ask_refresh_lv);
        mContentLv = mRefreshLv.getRefreshableView();
        mAskTvTop = (TextView) findViewById(R.id.ask_ask_tv_top);
        mAnswerNum = (TextView) findViewById(R.id.ask_header_anwser_tv);

        View footer = new View(this);
        AbsListView.LayoutParams params = new AbsListView.LayoutParams(-1, UIUtils.dip2px(52, this));
        footer.setLayoutParams(params);
        footer.setBackgroundColor(getResources().getColor(R.color.background));
        mContentLv.addFooterView(footer);
    }

    @Override
    protected void initAction() {
        mOthersAskTv.setOnClickListener(this);
        mAskTvTop.setOnClickListener(this);
        mQuestionTv.setOnClickListener(this);
        mRefreshLv.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (!is_load) {
                    resetData();
                    initData();
                }
            }
        });
        mRefreshLv.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!is_load && !is_end) {
                    is_load = true;
                    page++;
                    getFrontDataTask();
                }
            }
        });
    }


    @Override
    protected void initData() {
        getHeaderInfo();
        getFrontDataTask();
    }

    private void getHeaderInfo() {
        mHelper.getHeaderInfo(ouid, new AskHelper.GetAskdata() {
            @Override
            public void succ(String json) {
                getHeaderInfoSuccess(json);
            }

            @Override
            public void fail(String fail) {
                mProgressbarHelper.onFailed();
            }
        });
    }

    private void getFrontDataTask() {
        mHelper.getFrontData(ouid, page, new AskHelper.GetAskdata() {
            @Override
            public void succ(String json) {
                try {
                    List<Ask> templist = AskFactory.createAsk(json);
                    renderData(templist);
                    renderNoDataView(templist);
                } catch (Exception e) {
                    onError();
                }
            }

            @Override
            public void fail(String fail) {
                onError();
            }
        });
    }

    private void onError() {
        mProgressbarHelper.onFailed();
        mRefreshLv.onRefreshComplete();
        is_load = false;
    }

    private void renderNoDataView(List<Ask> templist) {
        if (page == 1 && templist.isEmpty()) {
            mProgressbarHelper.onNodata("", true);
            mRefreshLv.onRefreshComplete();
            is_load = false;
            is_end = true;
        }
    }


    public void getHeaderInfoSuccess(String result) {
        try {
            if (!TextUtils.isEmpty(result)) {
                Gson gson = new Gson();
                askHeaderInfo = gson.fromJson(result, AskHeaderInfo.class);
            }
            if (askHeaderInfo.is_author()) {
                mOthersAskTv.setVisibility(View.INVISIBLE);
                mQuestionTv.setVisibility(View.VISIBLE);
                if ("0".equals(askHeaderInfo.getAsk_count())) {
                    mQuestionTv.setText(getResources().getString(R.string.unansweredquestion));
                } else {
                    mQuestionTv.setText(String.format(getString(R.string.wait_to_answer), askHeaderInfo.getAsk_count()));
                }
                mAnswerNum.setText(String.format(getString(R.string.receive_gouda_mine), askHeaderInfo.getAnswer_count()));
                mAskTvTop.setVisibility(View.VISIBLE);
                FlagUtils.newAskNum = Integer.valueOf(askHeaderInfo.getAsk_count());
            } else {
                mQuestionTv.setVisibility(View.INVISIBLE);
                mOthersAskTv.setVisibility(View.VISIBLE);
                mAnswerNum.setText(String.format(getString(R.string.response), mName, askHeaderInfo.getAnswer_count()));
                mAskTvTop.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void renderData(List<Ask> templist) {
        if (page == 1) {
            alist.clear();
        }
        alist.addAll(templist);
        if (templist.size() == 0) {
            is_end = true;
        }
        if (mAdapter == null) {
            mAdapter = new AskListviewAdapter(this, alist, StringUtil.notNullEndWith(ouid, UserDataHelper.getInstance(this).getUid()));
            mContentLv.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        mProgressbarHelper.onSuccess();
        mRefreshLv.onRefreshComplete();
        is_load = false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ask_othersask_tv:
            case R.id.ask_ask_tv_top:
                doAsk();
                break;
            case R.id.ask_question_tv:
                doQuestion();
                break;
            case R.id.iv_back:
                finish();
                break;
            default:
                break;
        }
    }

    private void doAsk() {
        if (askHeaderInfo != null) {
            Intent intent = new Intent(this, WriteAskActivity.class);
            intent.putExtra(gotoUtil.INTENT_VALUE_ONE, ouid);
            intent.putExtra(gotoUtil.INTENT_VALUE_TWO, String.valueOf(askHeaderInfo.getAnonymous()));
            startActivityForResult(intent, FROM_ASK);
        }
    }

    private void doQuestion() {
        Intent intent = new Intent(this, QuestionActivity.class);
        startActivityForResult(intent, FROM_ASK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FROM_ASK) {
            getHeaderInfo();
        }
    }

    @Override
    public void onEventHappen(int eventCode, String message, Object object) {
        switch (eventCode) {
            case BaseObserver.ASK_REFRESH:
                askHeaderInfo.setAnswer_count(String.valueOf(Integer.valueOf(askHeaderInfo.getAnswer_count()) - 1));
                askHeaderInfo.setAsk_count(String.valueOf(Integer.valueOf(askHeaderInfo.getAsk_count()) + 1));
                getHeaderInfoSuccess("");
                break;
        }
    }
}